package ru.pb.game.network.engine.client.packets.receivable;

import ru.pb.game.data.xml.holders.ChannelHolder;
import ru.pb.game.network.engine.client.packets.FromClientToGameServerPacket;
import ru.pb.game.network.engine.client.packets.sendable.PROTOCOL_LOBBY_JOIN_ROOM_ACK;
import ru.pb.game.network.engine.client.packets.sendable.opcode_279_ACK;
import ru.pb.game.network.engine.client.packets.sendable.opcode_3653_ACK;
import ru.pb.game.objects.model.CHANNEL;
import ru.pb.game.objects.model.players.Player;
import ru.pb.game.objects.model.room.Room;
import ru.pb.game.objects.storage.ObjectsStorage;

public class PROTOCOL_LOBBY_JOIN_ROOM_REQ extends FromClientToGameServerPacket
{
	private int _roomid;

	@Override
	public void readImpl()
	{
		readH();
		_roomid = readD();
	}

	@Override
	public void runImpl()
	{
		Player p = getPlayer();
		if(p == null || getClient() == null)
		{
			return;
		}

		CHANNEL ch = ChannelHolder.getChannel(getClient().getChannelId());
		Room r = ch.getRoom(_roomid);
		if(r != null)
		{
			r.addPlayer(p);
			Player member = null;
			for(int objId : r.getAllPlayers().toArray())
			{
				member = ObjectsStorage.getInstance().getPlayer(objId);
				if(member != p)
				{
					member.sendPacket(new opcode_3653_ACK(p));
					member.sendPacket(new opcode_279_ACK(p));
					_log.info("Send packet player = " + p.getName());
				}
			}
			p.sendPacket(new PROTOCOL_LOBBY_JOIN_ROOM_ACK(p));
		}
	}
}